package mvc.core.impl;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
//import java.util.ResourceBundle;

import mvc.image.MachuImage;
import mvc.importer.IImporter;
import mvc.utils.FileUtilitys;
//import mvc.utils.MPResourceBundle;

import com.google.inject.Inject;

/**
 * Part of the core, handling the logic when importing files.
 * 
 * @author Joel
 * 
 */
public class ImportHandler {
	private final IImporter importer;
	//private ResourceBundle messages;

	/**
	 * Constructur used by Google Guice.
	 * 
	 * @param importer
	 */
	@Inject
	public ImportHandler(IImporter importer) {
		this.importer = importer;
	}

	/**
	 * Returns the images imported.
	 * 
	 * @param uniqueRuntimePath
	 *            Path to this runtime path
	 * 
	 * @return Returns a list of MachuImages that have been imported.
	 * @throws IOException
	 *             Throws a IOException when there is some kind of problem with
	 *             the import.
	 */
	public List<MachuImage> getImages(String uniqueRuntimePath)
			throws IOException {
		//messages = MPResourceBundle.getResourceBundle();
		List<MachuImage> imageList = new LinkedList<MachuImage>();
		File path = new File(uniqueRuntimePath);
		List<File> files = importer.getFiles();

		if (path.exists() == false && files.size() > 0) {
			if (path.mkdir()) {
				// System.out
				//						.println(messages.getString("created") + " " + messages.getString("Directory") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
				// + path.getAbsolutePath());

			} else {
				throw new IOException("Directory could not be created!"); //$NON-NLS-1$
			}

		}
		if (path.exists() && files.size() > 0) {
			for (File f : files) {
				File newFile = new File(path.getAbsolutePath() + File.separator
						+ f.getName());
				int i = 0;
				while (newFile.exists()) {
					newFile = new File(path.getAbsolutePath() + File.separator
							+ i + f.getName());
					i++;
				}
				FileUtilitys.copyFile(f, newFile);
				// System.out
				//						.println(messages.getString("created") + " " + messages.getString("file")//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
				// + newFile.getAbsolutePath());
				imageList.add(new MachuImage(newFile));
			}
		}

		return imageList;
	}
}